package vip.zhenzicheng.rabbitmq.helloworld;

import com.rabbitmq.client.*;
import vip.zhenzicheng.rabbitmq.utils.RabbitConstant;
import vip.zhenzicheng.rabbitmq.utils.RabbitUtils;

import java.io.IOException;

/**
 * @author zhenzicheng
 * @DESCRIPTION: 消费者 demo
 * @DATE: 2022/04/24 2:20 PM
 */
public class Consumer {
  public static void main(String[] args) throws IOException {
    // 获取TCP长连接
    Connection conn = RabbitUtils.getConnection();
    // 创建信道 相当于TCP中的虚拟连接
    Channel channel = conn.createChannel();

    channel.queueDeclare(RabbitConstant.QUEUE_HELLOWORLD, false, false, false, null);
    // 从MQ服务器中获取数据
    /*
     * @param s 队列
     * @param b 是否自动确认收到消息，false代表手动编程确认消息，MQ推荐
     * @param consumer 传入DefaultConsumer的实现类
     */
    channel.basicConsume(RabbitConstant.QUEUE_HELLOWORLD, false, new Receiver(channel));
  }

}

class Receiver extends DefaultConsumer {
  private final Channel channel;

  public Receiver(Channel channel) {
    super(channel);
    this.channel = channel;
  }

  @Override
  public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
    String msg = new String(body);
    System.out.println("消费者接收到消息：" + msg);
    System.out.println("消费的TagId" + envelope.getDeliveryTag());
    // 消息签收 只当前消费者才能签收
    channel.basicAck(envelope.getDeliveryTag(), false);

  }

}
